const {findFlagList, findRoleCreepsByRoom, findRoleCreepsByAll, findBuilding, findStore} = require("./Find");
const {canReserveRoom, MyRoomList, reserveRoom} = require("./Param");
//判断收集兵生成
module.exports.generateHarvest = generateHarvest = (room) => {
    let allHarvest = findRoleCreepsByRoom(room, "收集兵").filter(creep => creep.ticksToLive > 60);//获取房间内所有收集兵
    let sourceList = room.find(FIND_SOURCES);//获取房间内能量资源
    //拼接矿物资源集合
    if (room.find(FIND_STRUCTURES, {filter: site => site.structureType === STRUCTURE_EXTRACTOR}).length > 0) {
        sourceList = sourceList.concat(room.find(FIND_MINERALS, {filter: minerals => minerals.mineralAmount > 20000}))
    }
    //遍历资源集合
    for (let source of sourceList) {
        let sourceWork = allHarvest.filter(creep => creep.memory.source === source.id);
        let cacheWork = room.memory.harvestList.filter(creep => creep.source === source.id);
        if (sourceWork.length + cacheWork.length < 1) {
            if (room.energyAvailable >= 4000) {
                room.memory.harvestList.push({
                    level: 5,
                    source: source.id,
                    name: createName("收集兵", 5),
                    spawning: false
                });
                continue;
            }
            if (room.energyAvailable >= 2500) {
                room.memory.harvestList.push({
                    level: 4,
                    source: source.id,
                    name: createName("收集兵", 4),
                    spawning: false
                });
                continue;
            }
            if (room.energyAvailable >= 1500) {
                room.memory.harvestList.push({
                    level: 3,
                    source: source.id,
                    name: createName("收集兵", 3),
                    spawning: false
                });
                continue;
            }
            if (room.energyAvailable >= 550) {
                room.memory.harvestList.push({
                    level: 2,
                    source: source.id,
                    name: createName("收集兵", 2),
                    spawning: false
                });
                continue;
            }
            room.memory.harvestList.push({level: 1, source: source.id, name: createName("收集兵", 1), spawning: false});
        }
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.harvestList, allHarvest);//清除已生成的缓存
    }
    return room.memory.harvestList.length > 0;
}

//判断管家生成
module.exports.generateButler = generateButler = (room) => {
    let allButler = findRoleCreepsByRoom(room, "管家").filter(creep => creep.ticksToLive > 200);
    if (room.controller.level >= 8) {
        if (allButler.length + room.memory.butlerList.length < 1) {
            if(room.energyAvailable >= 3500){
                room.memory.butlerList.push({level: 4, name: createName("管家", 4), spawning: false})
                return true;
            }
            room.memory.butlerList.push({level: 1, name: createName("管家", 1), spawning: false})
        }
        return true;
    }
    if (allButler.length + room.memory.butlerList.length < 2) {
        if (room.energyAvailable >= 3500) {
            room.memory.butlerList.push({level: 4, name: createName("管家", 4), spawning: false})
            return true;
        }
        if (room.energyAvailable >= 1500) {
            room.memory.butlerList.push({level: 3, name: createName("管家", 3), spawning: false})
            return true;
        }
        if (room.energyAvailable >= 550) {
            room.memory.butlerList.push({level: 2, name: createName("管家", 2), spawning: false})
            return true;
        }
        room.memory.butlerList.push({level: 1, name: createName("管家", 1), spawning: false})
        return true;
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.butlerList, allButler);//清除已生成的缓存
    }
    return room.memory.butlerList.length > 0;
}
//判断守护兵生成
module.exports.generateGuard = generateGuard = (room) => {
    let canCreateReserve = false;
    let reserveRoomList;
    for (let i = 0; i < canReserveRoom.length; i++) {
        if (canReserveRoom[i] === room.name) {
            canCreateReserve = true;
            reserveRoomList = reserveRoom[i];
            break;
        }
    }
    if (!canCreateReserve) {
        return false
    }
    let flagReserveList = findFlagList("guard").filter(flag => {
        for (let roomName of reserveRoomList) {
            if (flag.pos.roomName === roomName) {
                return true;
            }
        }
        return false;
    })
    for (let flag of flagReserveList) {
        let roomGuardList = findRoleCreepsByAll("守护兵").filter(guardCreep => guardCreep.memory.guardRoom === flag.pos.roomName && guardCreep.ticksToLive > 200);
        let cacheGuard = room.memory.guardList.filter(guardCreep => guardCreep.guardRoom === flag.pos.roomName);
        if (roomGuardList.length + cacheGuard.length < 2) {
            room.memory.guardList.push({
                level: 1,
                guardRoom: flag.pos.roomName,
                name: createName("守护兵", 1),
                spawning: false
            });
        }
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.guardList, findRoleCreepsByAll("守护兵"));//清除已生成的缓存
    }
    return room.memory.guardList.length > 0;
}
//判断维修兵生成
module.exports.generateRepair = generateRepair = (room) => {
    let allRepair = findRoleCreepsByRoom(room, "维修兵").filter(creep => creep.ticksToLive > 200);
    if (allRepair.length + room.memory.repairList.length < 1) {
        if (room.energyAvailable > 1500) {
            room.memory.repairList.push({level: 5, name: createName("维修兵", 5), spawning: false});
            return;
        }
        if (room.energyAvailable > 650) {
            room.memory.repairList.push({level: 2, name: createName("维修兵", 2), spawning: false});
            return;
        }
        room.memory.repairList.push({level: 1, name: createName("维修兵", 1), spawning: false});
        return;
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.repairList, allRepair);//清除已生成的缓存
    }
    return room.memory.repairList.length > 0;
}

//判断建造兵生成
module.exports.generateBuilder = generateBuilder = (room) => {
    let siteList = findBuilding(room);
    let fullStore = findStore(room, 1);
    let allBuild = findRoleCreepsByRoom(room, "建造兵").filter(creep => creep.ticksToLive > 200);//获取建造兵数量
    //如果controller等级过低
    if (room.controller.level < 3 && fullStore.length > 0 && allBuild.length + room.memory.builderList.length < 2) {
        room.memory.builderList.push({level: 1, name: createName("建造兵", 1), spawning: false});
        return true;
    }
    if (siteList.length <= 0 || fullStore.length < 2) {//如果不存在建筑,结束
        room.memory.builderList = [];
        return false;
    }
    //获取超过1000容量的容器
    if (allBuild.length + room.memory.builderList.length < 2) {
        if (room.energyAvailable > 1500) {
            room.memory.builderList.push({level: 5, name: createName("建造兵", 5), spawning: false});
            return true;
        }
        if (room.energyAvailable > 650) {
            room.memory.builderList.push({level: 2, name: createName("建造兵", 2), spawning: false});
            return true;
        }
        room.memory.builderList.push({level: 1, name: createName("建造兵", 1), spawning: false});
        return true;
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.builderList, allBuild);//清除已生成的缓存
    }
    return room.memory.builderList.length > 0;
}

//判断升级兵生成
module.exports.generateUp = generateUp = (room) => {
    if (room.controller.level >= 8) {
        return false;
    }
    let allUp = findRoleCreepsByRoom(room, "升级兵").filter(creep => creep.ticksToLive > 200);
    //获取超过1000容量的容器
    let containersWithResources = room.find(FIND_STRUCTURES, {filter: structure => (structure.structureType === STRUCTURE_CONTAINER || structure.structureType === STRUCTURE_STORAGE) && structure.store.getUsedCapacity() > 1000});
    if (room.storage && room.storage.usedStore() > 500 * 1000 && allUp.length + room.memory.upList.length < 2 && room.energyAvailable > 3500) {
        room.memory.upList.push({level: 4, name: createName("升级兵", 4), spawning: false});
        return true;
    }
    if (containersWithResources.length > 3 && allUp.length + room.memory.upList.length < 5 && room.energyAvailable > 1500) {
        room.memory.upList.push({level: 5, name: createName("升级兵", 5), spawning: false})
        return true;
    }
    if (containersWithResources.length > 3 && allUp.length + room.memory.upList.length < 2) {
        if (room.energyAvailable > 850) {
            room.memory.upList.push({level: 2, name: createName("升级兵", 2), spawning: false})
        } else {
            room.memory.upList.push({level: 1, name: createName("升级兵", 1), spawning: false})
        }
        return true;
    }
    if (allUp.length + room.memory.upList.length < 1 && room.energyAvailable > 500) {
        room.memory.upList.push({level: 1, name: createName("升级兵", 1), spawning: false})
        return true;
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.upList, allUp);//清除已生成的缓存
    }
    return room.memory.upList.length > 0;
}

//判断防御兵生成
module.exports.generateDefense = generateDefense = (room) => {
    let hostileList = room.find(FIND_HOSTILE_CREEPS);
    let allDefense = findRoleCreepsByRoom(room, "防御兵");
    if (allDefense.length + room.memory.defenseList.length < 2 && hostileList.length > 1) {
        if (room.energyAvailable > 3000) {
            room.memory.defenseList.push({level: 3, name: createName("防御兵", 3), spawning: false});
            return true;
        }
        if (room.energyAvailable > 650) {
            room.memory.defenseList.push({level: 2, name: createName("防御兵", 2), spawning: false});
            return true;
        }
        room.memory.defenseList.push({level: 1, name: createName("防御兵", 1), spawning: false});
        return true;
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.defenseList, allDefense);//清除已生成的缓存
    }
}

//判断外矿收集者生成
module.exports.generateOutHarvest = generateOutHarvest = (room) => {
    let canCreateReserve;
    let reserveRoomList;
    for (let i = 0; i < canReserveRoom.length; i++) {
        if (canReserveRoom[i] === room.name) {
            canCreateReserve = true;
            reserveRoomList = reserveRoom[i];
            break;
        }
    }
    if (!canCreateReserve) {
        return false
    }
    let flagReserveList = findFlagList("resource").filter(flag => {
        for (let roomName of reserveRoomList) {
            if (flag.pos.roomName === roomName) {
                return true;
            }
        }
        return false;
    })
    let allCreeps = findRoleCreepsByAll("外矿收集兵").filter(creep => creep.ticksToLive > 200);
    for (let resourceFlag of flagReserveList) {
        if (resourceFlag.room) {
            let realResource = resourceFlag.room.lookForAt(LOOK_SOURCES, resourceFlag.pos)[0];
            let allOutHarvestByResource = allCreeps.filter(creep => creep.memory.source === realResource.id);
            let cacheWork = room.memory.outHarvestList.filter(creep => creep.source === realResource.id);
            if (allOutHarvestByResource.length + cacheWork.length < 1) {
                if (room.energyAvailable > 1500) {
                    room.memory.outHarvestList.push({
                        level: 2,
                        source: realResource.id,
                        flagRoomName: resourceFlag.room.name,
                        name: createName("外矿收集兵", 2),
                        spawning: false
                    })
                    continue;
                }
                room.memory.outHarvestList.push({
                    level: 1,
                    source: realResource.id,
                    flagRoomName: resourceFlag.room.name,
                    name: createName("外矿收集兵", 1),
                    spawning: false
                })
            }
        }
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.outHarvestList, allCreeps);//清除已生成的缓存
    }
    return room.memory.outHarvestList.length > 0;
}

//判断预订兵生成
module.exports.generateReserve = generateReserve = (room) => {
    let canCreateReserve;
    let reserveRoomList;
    for (let i = 0; i < canReserveRoom.length; i++) {
        if (canReserveRoom[i] === room.name) {
            canCreateReserve = true;
            reserveRoomList = reserveRoom[i];
            break;
        }
    }
    if (!canCreateReserve) {
        return false
    }
    let flagReserveList = findFlagList("reserve").filter(flag => {
        for (let roomName of reserveRoomList) {
            if (flag.pos.roomName === roomName) {
                return true;
            }
        }
        return false;
    })
    //判断预订兵生成
    for (let flag of flagReserveList) {
        let allFlagReserve = findRoleCreepsByAll("预订兵").filter(creep => creep.memory.reserveRoom === flag.pos.roomName);
        let cacheReserve = room.memory.reserveList.filter(item => item.reserveRoom === flag.pos.roomName);
        if (allFlagReserve.length + cacheReserve.length < 1) {
            if (Game.rooms[flag.pos.roomName] && Game.rooms[flag.pos.roomName].controller.reservation && !Game.rooms[flag.pos.roomName].controller.my) {//如果存在检查预订时间
                let ticksToEnd = Game.rooms[flag.pos.roomName].controller.reservation.ticksToEnd;
                if (ticksToEnd < 500) {//如果小于1500,去补充时间
                    if (room.energyAvailable >= 2500) {
                        room.memory.reserveList.push({
                            level: 3,
                            reserveRoom: flag.pos.roomName,
                            name: createName("预订兵", 3),
                            spawning: false
                        })
                        continue;
                    }
                    if (room.energyAvailable >= 1000) {
                        room.memory.reserveList.push({
                            level: 2,
                            reserveRoom: flag.pos.roomName,
                            name: createName("预订兵", 2),
                            spawning: false
                        })
                        continue;
                    }
                    if (room.energyAvailable >= 550) {
                        room.memory.reserveList.push({
                            level: 1,
                            reserveRoom: flag.pos.roomName,
                            name: createName("预订兵", 1),
                            spawning: false
                        })
                    }
                }
            } else {//代表还没有预订,需要创建
                room.memory.reserveList.push({
                    level: 1,
                    reserveRoom: flag.pos.roomName,
                    name: createName("预订兵", 1),
                    spawning: false
                });
            }
        }
    }
    if (Game.time % 20 === 0) {
        clearCacheList(room.memory.reserveList, findRoleCreepsByAll("预订兵"));//清除已生成的缓存
    }
    return room.memory.reserveList > 0;
}
/**
 * 判断是否生成creep
 */
module.exports.judgeCreateCreeps = () => {
    for (let i = 0; i < MyRoomList.length; i++) {//遍历我设定的房间
        let room = Game.rooms[MyRoomList[i]]
        let canHarvest = generateHarvest(room);
        let canDefense = generateDefense(room);
        let canButler = generateButler(room);
        let canRepair = generateRepair(room);
        let canBuilder = generateBuilder(room);
        let canUp = generateUp(room);
        let canOutHarvest = generateOutHarvest(room);
        let canReserve = generateReserve(room);
        let canGuard = generateGuard(room);
        if (!(canHarvest || canDefense || canButler || canRepair || canBuilder || canUp || canOutHarvest || canReserve || canGuard)) {
            room.memory.mustSpawning = false;
        }
    }
}
/**
 * 创建士兵
 * @param name
 * @param role 行为
 * @param level 级别
 * @param spawn
 * @param other 附属属性
 * @param other2
 */
module.exports.create = create = (name = null, role, level, spawn, other = null, other2 = null) => {
    let body = [];
    //设置内存
    let memory = {role: role, createSpawn: spawn.name};
    switch (role) {
        case "收集兵":
            // 定义新 Creep 的属性
            switch (level) {
                case 1:
                    body = [...Array(1).fill(CARRY), ...Array(2).fill(WORK), ...Array(1).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(1).fill(CARRY), ...Array(4).fill(WORK), ...Array(1).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(1).fill(CARRY), ...Array(6).fill(WORK), ...Array(3).fill(MOVE)];
                    break;
                case 4:
                    body = [...Array(3).fill(CARRY), ...Array(17).fill(WORK), ...Array(10).fill(MOVE)];
                    break;
                case 5:
                    body = [...Array(5).fill(CARRY), ...Array(28).fill(WORK), ...Array(17).fill(MOVE)];
                    break;
            }
            memory.source = other;
            break;
        case "外矿收集兵":
            switch (level) {
                case 1:
                    body = [...Array(3).fill(WORK), ...Array(2).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(6).fill(WORK), ...Array(3).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(8).fill(WORK), ...Array(8).fill(MOVE)];
                    break;
            }
            memory.source = other;
            memory.harvestRoom = other2;
            break;
        case "管家":
            switch (level) {
                case 1:
                    body = [...Array(3).fill(CARRY), ...Array(2).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(6).fill(CARRY), ...Array(3).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(16).fill(CARRY), ...Array(8).fill(MOVE)];
                    break;
                case 4:
                    body = [...Array(33).fill(CARRY), ...Array(17).fill(MOVE)];
                    break;
            }
            break;
        case "建造兵":
        case "维修兵":
        case "升级兵":
            switch (level) {
                case 1:
                    body = [...Array(2).fill(CARRY), ...Array(1).fill(WORK), ...Array(2).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(3).fill(CARRY), ...Array(4).fill(WORK), ...Array(4).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(5).fill(CARRY), ...Array(15).fill(WORK), ...Array(7).fill(MOVE)];
                    break;
                case 4:
                    body = [...Array(13).fill(CARRY), ...Array(20).fill(WORK), ...Array(17).fill(MOVE)];
                    break;
                case 5:
                    body = [...Array(5).fill(CARRY), ...Array(10).fill(WORK), ...Array(7).fill(MOVE)];
                    break;
            }
            break;
        case "战士":
            switch (level) {
                case 1:
                    body = [...Array(5).fill(TOUGH), ...Array(5).fill(ATTACK), ...Array(10).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(10).fill(ATTACK), ...Array(10).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(10).fill(TOUGH), ...Array(15).fill(ATTACK), ...Array(25).fill(MOVE)];
                    break;
            }
            break;
        case "盾牌兵":
            switch (level) {
                case 1:
                    body = [...Array(20).fill(TOUGH), ...Array(10).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(33).fill(TOUGH), ...Array(17).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(20).fill(TOUGH), ...Array(13).fill(HEAL), ...Array(17).fill(MOVE)];
                    break;
            }
            break;
        case "占领兵":
            switch (level) {
                case 1:
                    body = [CLAIM, MOVE];
                    break;
            }
            break;
        case "预订兵":
            switch (level) {
                case 1:
                    body = [CLAIM, MOVE];
                    break;
                case 2:
                    body = [...Array(2).fill(CLAIM), ...Array(2).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(3).fill(CLAIM), ...Array(3).fill(MOVE)];
                    break;
            }
            memory.reserveRoom = other;
            break;
        case "外部搬运兵":
            switch (level) {
                case 1:
                    body = [...Array(4).fill(CARRY), ...Array(2).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(8).fill(CARRY), ...Array(4).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(16).fill(CARRY), ...Array(8).fill(MOVE)];
                    break;
                case 4:
                    body = [...Array(33).fill(CARRY), ...Array(17).fill(MOVE)];
                    break;
            }
            memory.source = other
            break;
        case "外部维修兵":
            switch (level) {
                case 1:
                    body = [...Array(2).fill(CARRY), ...Array(2).fill(WORK), ...Array(2).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(3).fill(CARRY), ...Array(3).fill(WORK), ...Array(4).fill(MOVE), ...Array(2).fill(ATTACK)];
                    break;
                case 3:
                    body = [...Array(5).fill(CARRY), ...Array(5).fill(WORK), ...Array(6).fill(MOVE), ...Array(2).fill(ATTACK)];
                    break;
                case 4:
                    body = [...Array(13).fill(CARRY), ...Array(20).fill(WORK), ...Array(17).fill(MOVE)];
                    break;
            }
            memory.source = other
            break;
        case "守护兵":
            switch (level) {
                case 1:
                    body = [...Array(5).fill(TOUGH), ...Array(18).fill(MOVE), ...Array(17).fill(ATTACK), ...Array(10).fill(HEAL)]
            }
            memory.guardRoom = other;
            break;
        case "防御兵":
            switch (level) {
                case 1:
                    body = [...Array(4).fill(TOUGH), ...Array(2).fill(ATTACK), ...Array(2).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(8).fill(TOUGH), ...Array(4).fill(ATTACK), ...Array(5).fill(MOVE)];
                    break;
                case 3:
                    body = [...Array(10).fill(TOUGH), ...Array(23).fill(ATTACK), ...Array(17).fill(MOVE)];
                    break;
            }
            break;
        case "拆迁兵":
            switch (level) {
                case 1:
                    body = [...Array(10).fill(WORK), ...Array(10).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(25).fill(WORK), ...Array(25).fill(MOVE)];
                    break;
            }
            break;
        case "土匪":
            switch (level) {
                case 1:
                    body = [...Array(10).fill(CARRY), ...Array(10).fill(MOVE)];
                    break;
                case 2:
                    body = [...Array(25).fill(CARRY), ...Array(25).fill(MOVE)];
                    break;
            }
            break;
        default:
            break;
    }
    // 使用不同的名字以避免冲突
    if (name === null) {
        name = createName(role, level)
    }
    if (memory === "" || Object.values(memory).length === 0) {
        return false
    }
    // 向兵营发起孵化 Creep 的请求
    let result = spawn.spawnCreep(body, name, {memory: memory});
    // 处理孵化结果
    if (result === OK) {
        log(spawn.name + ':正在孵化Creep: ' + name, "success");
        return 0;
    } else if (result === -3) {
        log(spawn.name + ':孵化[' + name + ']异常: 存在相同名字', "warning");
        return -3;
    } else {
        spawn.room.memory.mustSpawning = true;
        if (result === ERR_NOT_ENOUGH_ENERGY) {
            log(spawn.name + ':孵化[' + name + ']异常: 能源不足,能量剩余:' + spawn.room.energyAvailable, "warning");
        } else if (result === ERR_BUSY) {
            log(spawn.name + ':孵化[' + name + ']异常: 正在孵化:' + spawn.spawning.name + ",剩余:" + spawn.spawning.remainingTime + "s", "warning");
        } else {
            log(spawn.name + ':孵化[' + name + ']异常: ' + result, "warning");
        }
        return false;
    }
}
let createName = (role, level) => {
    return (role + '_lv' + level + '_' + Game.time + '_' +Math.floor(Math.random() * 1000) * Math.random() * 10 * Game.time).substring(0,20-Math.floor(Math.random()*10));
}
//删除缓存
let clearCacheList = (cacheList, creepList) => {
    for (let i = 0; i < cacheList.length; i++) {
        if (cacheList[i].spawning) {
            for (let creep of creepList) {
                if (creep.name === cacheList[i].name) {
                    cacheList.splice(i, 1);
                    console.log("已生成士兵:", creep.name, creep,"清除缓存")
                    return;
                }
            }
        }
    }
}
//日志系统
let log = (content, level = "info") => {
    if (content !== undefined && content !== "" && content != null) {
        let levelColor;
        let levelTitle;
        switch (level) {
            case "success":
                levelColor = "background-color:#67c23a";
                levelTitle = "成功";
                break;
            case "warning":
                levelColor = "background-color:#e6a23c";
                levelTitle = "警告";
                break;
        }
        console.log(`<span style="${levelColor};color:white;border-radius: 2px;padding:1px 5px;font-size: 10px">${levelTitle}</span>` + "." + content);
    }
}